/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import com.mxrck.autocompleter.TextAutoCompleter;
import de.centigrade.bizlaf.BizLafControl;
import de.centigrade.bizlaf.support.BizLafStyles;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import resources.local_connection;
import resources.queries;

/**
 * @author Pascual, Homeroe
 */
public final class editProducto extends javax.swing.JFrame {

    static Connection cn;
    static PreparedStatement ps;
    static ResultSet rs;
    //static DefaultListModel model2 = new DefaultListModel();
    boolean hayImagen = false;
    int cproveedor, i = 1, codigo;
    Vector<Integer> sucursales = new Vector<Integer>();
    static TextAutoCompleter textAutoCompleter;
    NumberFormat formatter = NumberFormat.getCurrencyInstance();
    public editProducto() {
        initComponents();
        WindowListener exitListener = new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                salir.doClick();
            }
        };
        this.addWindowListener(exitListener);
        BizLafControl.get().setStyle(jPanel3, BizLafStyles.CONTAINER);
        BizLafControl.get().setStyle(id_producto, BizLafStyles.BADGE);
        if (!Almacen.precios) {
            jPanel2.setVisible(false);
        }
        if (Almacen.celulares) {
            fecha.setVisible(false);
            tipo.removeAllItems();
            tipo.addItem("Producto");
            tipo.addItem("Celular");
            tipo.addItem("Chip");
        }
        try {

            textAutoCompleter = new TextAutoCompleter(marca);
            textAutoCompleter.setMode(0);
            textAutoCompleter.setCaseSensitive(false);

            cantidadStock.setDocument(new LimitadorCaracteres());
           // id_producto.setDocument(new LimitadorCaracteres());
            cantidadStock.setDocument(new LimitadorCaracteres());
            minimoStock.setDocument(new LimitadorCaracteres());
            peso.setDocument(new LimitadorCaracteresInt());
            preciocompra.setDocument(new LimitadorCaracteres());
            textPrecio1.setDocument(new LimitadorCaracteres());
            textPrecio2.setDocument(new LimitadorCaracteres());
            textPrecio3.setDocument(new LimitadorCaracteres());
            textCantidad1.setDocument(new LimitadorCaracteres());
            textCantidad1.setText("1");
            textCantidad2.setDocument(new LimitadorCaracteres());
            textCantidad3.setDocument(new LimitadorCaracteres());
            fecha.setEnabled(false);
            activo.setSelectedIndex(1);
            comboSucursal.addItem("Todas");
            cn = local_connection.getconnect();
            textAutoCompleter.removeAll();
            ps = (PreparedStatement) cn.prepareStatement("select marca from productos group by marca");
            rs = ps.executeQuery();
            while (rs.next()) {
                if (rs.getString(1) != null) {
                    textAutoCompleter.addItem(rs.getString(1));
                }
            }
            ps = (PreparedStatement) cn.prepareStatement("SELECT * FROM sucursales");
            rs = ps.executeQuery();
            while (rs.next()) {
                comboSucursal.addItem(rs.getString("nombre"));
                sucursales.add(rs.getInt("id"));
                i++;
            }
            cargarProveedores();
            nuevoProducto();
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    void nuevoProducto() {
        try {
            ps = (PreparedStatement) cn.prepareStatement("select id_producto from productos order by id_producto desc  limit 1");
            rs = ps.executeQuery();
            if(rs.next())
            codigo = rs.getInt("id_producto") + 1;
            else codigo=1;
            id_producto.setText(String.valueOf(codigo));
            /*model2.removeAllElements();
            model2.clear();*/
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        jLabel18 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        activo = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        peso = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jLabel12 = new javax.swing.JLabel();
        minimoStock = new javax.swing.JTextField();
        cantidadStock = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        ubicacionStock = new javax.swing.JTextField();
        comboSucursal = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        categorias = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        textNombre1 = new javax.swing.JTextField();
        textCantidad1 = new javax.swing.JTextField();
        textPrecio1 = new javax.swing.JTextField();
        comboPorcentaje = new javax.swing.JComboBox();
        jLabel15 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        textNombre2 = new javax.swing.JTextField();
        textCantidad2 = new javax.swing.JTextField();
        textPrecio2 = new javax.swing.JTextField();
        labelSugerido = new javax.swing.JLabel();
        textNombre3 = new javax.swing.JTextField();
        textCantidad3 = new javax.swing.JTextField();
        textPrecio3 = new javax.swing.JTextField();
        jLabel23 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        descuento2 = new javax.swing.JComboBox();
        descuento3 = new javax.swing.JComboBox();
        precio2 = new javax.swing.JLabel();
        precio3 = new javax.swing.JLabel();
        precio1 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        tipo = new javax.swing.JComboBox();
        imageButton = new javax.swing.JButton();
        preciocompra = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        descripcion = new javax.swing.JTextArea();
        nombre = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        comboTipoProducto = new javax.swing.JComboBox();
        jLabel19 = new javax.swing.JLabel();
        marca = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        fecha = new javax.swing.JButton();
        jLabel20 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        notas = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        comboProveedor = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        salir = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        modelo = new javax.swing.JTextField();
        jLabel21 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        guardar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        imageProduct = new javax.swing.JLabel();
        id_producto = new javax.swing.JLabel();

        jLabel18.setText("jLabel18");

        jLabel6.setText("jLabel6");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Agregar nuevo producto");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());
        setResizable(false);

        activo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No", "Si" }));
        activo.setNextFocusableComponent(id_producto);
        activo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                activoActionPerformed(evt);
            }
        });

        jLabel1.setText("Activo:");

        peso.setNextFocusableComponent(preciocompra);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Asignar a Sucursal"));
        jPanel1.setToolTipText("");
        jPanel1.setName(""); // NOI18N

        jLabel12.setText("Sucursal");

        minimoStock.setEnabled(false);
        minimoStock.setNextFocusableComponent(peso);
        minimoStock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                minimoStockActionPerformed(evt);
            }
        });

        cantidadStock.setEnabled(false);

        jLabel10.setText("Minimo Stock:");

        jLabel9.setText("Stock: ");

        ubicacionStock.setEnabled(false);
        ubicacionStock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ubicacionStockActionPerformed(evt);
            }
        });

        comboSucursal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboSucursalActionPerformed(evt);
            }
        });

        jLabel3.setText("Ubicacion:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(ubicacionStock, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cantidadStock))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(comboSucursal, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                        .addComponent(jLabel10)
                        .addGap(18, 18, 18)
                        .addComponent(minimoStock, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(27, 27, 27))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(16, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(ubicacionStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(cantidadStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(minimoStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12)
                    .addComponent(comboSucursal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        categorias.setText("Categorias");
        categorias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                categoriasActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Precios de venta"));

        textNombre1.setText("Unitario");
        textNombre1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textNombre1ActionPerformed(evt);
            }
        });

        textCantidad1.setText("1");

        textPrecio1.setText("0");
        textPrecio1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textPrecio1ActionPerformed(evt);
            }
        });
        textPrecio1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                textPrecio1KeyReleased(evt);
            }
        });

        comboPorcentaje.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "20%", "30%", "50%", "100%", "150%", "200%", "250%", "300%", "350%", "400%", "450%" }));
        comboPorcentaje.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                comboPorcentajePopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });
        comboPorcentaje.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboPorcentajeActionPerformed(evt);
            }
        });

        jLabel15.setText("Nombre:");

        jLabel16.setText("Cantidad:");

        jLabel17.setText("Precio:");

        textNombre2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textNombre2ActionPerformed(evt);
            }
        });

        textCantidad2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textCantidad2ActionPerformed(evt);
            }
        });

        labelSugerido.setText("Precio sugerido: ");

        textNombre3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textNombre3ActionPerformed(evt);
            }
        });

        jLabel23.setText("Descuento:");

        jLabel24.setText("Sugerencia:");

        descuento2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5%", "10%", "15%", "20%", "25%", "30%" }));
        descuento2.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                descuento2PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        descuento3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "5%", "10%", "15%", "20%", "25%", "30%" }));
        descuento3.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
                descuento3PopupMenuWillBecomeInvisible(evt);
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
            }
        });

        precio2.setText("0.00");

        precio3.setText("0.00");

        precio1.setText("0.00");
        precio1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                precio1PropertyChange(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(comboPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(labelSugerido)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(precio1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel15)
                                .addGap(53, 53, 53))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(textNombre1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(textNombre3, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                                        .addComponent(textNombre2)))
                                .addGap(4, 4, 4)))
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(textCantidad1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel16))
                            .addComponent(textCantidad2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textCantidad3, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel17)
                            .addComponent(textPrecio1)
                            .addComponent(textPrecio2)
                            .addComponent(textPrecio3, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jLabel23)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel24))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(descuento2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(descuento3, 0, 69, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(precio2, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(precio3, javax.swing.GroupLayout.Alignment.TRAILING))))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboPorcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelSugerido)
                    .addComponent(precio1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(jLabel16)
                    .addComponent(jLabel17)
                    .addComponent(jLabel23)
                    .addComponent(jLabel24))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textCantidad1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textPrecio1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textNombre1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textNombre2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textCantidad2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textPrecio2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(descuento2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(precio2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textNombre3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textCantidad3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textPrecio3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(descuento3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(precio3))
                .addGap(27, 27, 27))
        );

        jLabel13.setText("Vender producto por:");

        jLabel14.setText("Gramos");

        tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Producto", "Servicio", "Curso" }));
        tipo.setNextFocusableComponent(modelo);
        tipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tipoActionPerformed(evt);
            }
        });

        imageButton.setText("Imagen");
        imageButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                imageButtonActionPerformed(evt);
            }
        });

        preciocompra.setText("0");
        preciocompra.setName(""); // NOI18N
        preciocompra.setNextFocusableComponent(comboTipoProducto);
        preciocompra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                preciocompraActionPerformed(evt);
            }
        });
        preciocompra.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                preciocompraKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                preciocompraKeyReleased(evt);
            }
        });

        descripcion.setColumns(20);
        descripcion.setRows(5);
        descripcion.setWrapStyleWord(true);
        jScrollPane1.setViewportView(descripcion);

        nombre.setNextFocusableComponent(tipo);

        jLabel7.setText("Notas:");

        comboTipoProducto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pieza", "Kilogramo", "Litro" }));
        comboTipoProducto.setNextFocusableComponent(guardar);

        jLabel19.setText("Pesos");

        jLabel8.setText("Nombre:");

        fecha.setText("Fecha");
        fecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fechaActionPerformed(evt);
            }
        });

        jLabel20.setText("Precio de compra:");

        notas.setColumns(20);
        notas.setRows(5);
        notas.setWrapStyleWord(true);
        notas.setNextFocusableComponent(ubicacionStock);
        jScrollPane3.setViewportView(notas);

        jLabel4.setText("Modelo:");

        jLabel5.setText("Descripcion General:");

        salir.setText("Salir");
        salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirActionPerformed(evt);
            }
        });

        jLabel2.setText("Tipo:");

        modelo.setNextFocusableComponent(peso);

        jLabel21.setText("Proveedor:");

        jLabel22.setText("Marca:");

        guardar.setText("Guardar");
        guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarActionPerformed(evt);
            }
        });

        jButton2.setText("Agregar Proveedor");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel11.setText("Peso:");

        imageProduct.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        id_producto.setText("---");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel5)
                    .addComponent(jLabel21)
                    .addComponent(jLabel13)
                    .addComponent(jLabel22)
                    .addComponent(jLabel11)
                    .addComponent(jLabel20)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2)
                    .addComponent(jLabel8)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(preciocompra, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel19))
                            .addComponent(modelo, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(tipo, 0, 155, Short.MAX_VALUE)
                            .addComponent(nombre)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel14))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(activo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(id_producto))
                            .addComponent(marca, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(comboTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(118, 118, 118)
                        .addComponent(guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(salir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(fecha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(imageProduct, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(imageButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(categorias, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {comboProveedor, comboTipoProducto, jButton2, jScrollPane1, jScrollPane3, marca, modelo, nombre, tipo});

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {peso, preciocompra});

        jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jPanel1, jPanel2});

        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(activo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(id_producto))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(4, 4, 4)
                        .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(modelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel14)
                            .addComponent(jLabel11))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(preciocompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel19)
                            .addComponent(jLabel20))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(marca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel22))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(comboTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel13))
                        .addGap(9, 9, 9)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel21))
                        .addGap(9, 9, 9)
                        .addComponent(jButton2)
                        .addGap(3, 3, 3)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel8)
                                .addGap(12, 12, 12)
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel4)
                                .addGap(184, 184, 184)
                                .addComponent(jLabel5)
                                .addGap(105, 105, 105)
                                .addComponent(jLabel7)
                                .addGap(0, 82, Short.MAX_VALUE))
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(imageButton, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(imageProduct, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(categorias)
                                    .addComponent(fecha))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(9, 9, 9)
                                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(guardar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(salir, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addContainerGap())))
        );

        jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {peso, preciocompra});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarActionPerformed
        System.out.println(String.valueOf(tipo.getSelectedItem()));
        if (nombre.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Ingresa el nombre del producto");
        } else if (preciocompra.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Ingresa el precio de compra del producto");
        } else {
            try {
                guardarDatosProductos();
            } catch (FileNotFoundException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }
        }


        // TODO add your handling code here:
    }//GEN-LAST:event_guardarActionPerformed

    private void guardarDatosProductos() throws FileNotFoundException {
        try {
            String name = String.valueOf(comboProveedor.getSelectedItem());
            int valor = 0;
             int productId = Integer.parseInt(id_producto.getText());
            valor = activo.getSelectedIndex();
            int persona = 0;
            ps = (PreparedStatement) cn.prepareStatement("SELECT * FROM personas WHERE concat(nombre,' ',paterno,' ',materno)='" + name + "' LIMIT 1");
            rs = ps.executeQuery();
            if (rs.next()) {
                persona = rs.getInt("id_persona");
            }
            else persona=0;
            if (descripcion.getText().equals("")) {
                descripcion.setText("NULL");
            }

            if (notas.getText().equals("")) {
                notas.setText("NULL");
            }
            if (modelo.getText().equals("")) {
                modelo.setText("NULL");
            }
            if (ubicacionStock.getText().equals("")) {
                ubicacionStock.setText("NULL");
            }
            if (cantidadStock.getText().equals("")) {
                cantidadStock.setText("0");
            }
            if (minimoStock.getText().equals("")) {
                minimoStock.setText("0");
            }
            if (peso.getText().equals("")) {
                peso.setText("0");
            }
            if (preciocompra.getText().equals("")) {
                preciocompra.setText("0");
            }
       /*     for (int j = 0; j < model2.getSize(); j++) {
                queries.doSyncQuery(cn, ps, "INSERT INTO categorias_productos VALUES ((SELECT id_categoria FROM categorias WHERE nombre = '" + model2.get(j) + "')," + codigo + ")");
            }*/
            ps = queries.doSyncQuery(cn, ps, "INSERT INTO productos("
                    + "id_producto,activo,nombre,tipo,modelo,descripcion,peso,notas,preciocompra,tipo_cantidad,id_proveedor,marca)"
                    + "VALUES ("+productId+",'" + activo.getSelectedIndex() + "','" + nombre.getText() + "','" + String.valueOf(tipo.getSelectedItem()) + "','" + modelo.getText() + "','" + descripcion.getText() + "','" + peso.getText() + "','" + notas.getText() + "','" + preciocompra.getText() + "','" + comboTipoProducto.getSelectedItem().toString() + "'," + persona + ",'" + marca.getText() + "')");
           // ResultSet rs = ps.getGeneratedKeys();
           // rs.next();
           
            int su = 0;
            if (comboSucursal.getSelectedIndex() != 0) {
                su = sucursales.elementAt(comboSucursal.getSelectedIndex());
            }
            // Vemos si se inicia con un stock, de no ser asi, crea uno en cero.
            if (comboSucursal.getSelectedIndex() == 0) {
                queries.doSyncQuery(cn, ps, "INSERT INTO stock(id_producto,cantidad,ubicacion,sucursal,minimo) VALUES(" + productId + ",0,'',0,0)");
                for (int j = 0; j < sucursales.size(); j++) {
                    insertPrecios( sucursales.elementAt(j), productId);
                }
            } else {
                queries.doSyncQuery(cn, ps, "INSERT INTO stock(id_producto,cantidad,ubicacion,sucursal,minimo) VALUES(" + productId + "," + cantidadStock.getText() + ",'" + ubicacionStock.getText() + "'," + su + "," + minimoStock.getText() + ")");
                insertPrecios(su, productId);
            }
            // Comprobamos que hay imagen
            if (hayImagen) {
                File file = fileChooser.getSelectedFile();
                FileInputStream fis = new FileInputStream(file);
                java.sql.PreparedStatement st;
                String ext = file.getName().split("\\.")[1];
                // Preparamos query para insertar el archivo
                ps = (PreparedStatement) cn.prepareStatement("INSERT INTO archivos(nombre,ext,archivo) VALUES(?,?,?)", Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, file.getName());
                ps.setString(2, ext);
                ps.setBinaryStream(3, fis, (int) file.length());
                ps.executeUpdate();
                // Hacemos relacion con el producto
                rs = ps.getGeneratedKeys();
                rs.next();
                ps = (PreparedStatement) cn.prepareStatement("INSERT INTO archivo_relacion(archivoId,productoId) VALUES(?,?)");
                ps.setInt(1, rs.getInt(1));
                ps.setInt(2, productId);
                ps.execute();
            }
            this.dispose();
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }

    }

    private void insertPrecios(int su, int productId) {
        // Metemos registro de precios
        if (!textNombre1.getText().isEmpty() && !textPrecio1.getText().isEmpty()) {
            queries.doSyncQuery(cn, ps, "INSERT INTO precios(id_producto,nombre,cantidad,precio,sucursal)"
                    + " VALUES(" + productId + ",'" + textNombre1.getText() + "'," + textCantidad1.getText() + "," + textPrecio1.getText() + "," + su + ")");
        }
        if (!textNombre2.getText().isEmpty() && !textPrecio2.getText().isEmpty()) {
            queries.doSyncQuery(cn, ps, "INSERT INTO precios(id_producto,nombre,cantidad,precio,sucursal)"
                    + " VALUES(" + productId + ",'" + textNombre2.getText() + "'," + textCantidad2.getText() + "," + textPrecio2.getText() + "," + su + ")");
        }
        if (!textNombre3.getText().isEmpty() && !textPrecio3.getText().isEmpty()) {
            queries.doSyncQuery(cn, ps, "INSERT INTO precios(id_producto,nombre,cantidad,precio,sucursal)"
                    + " VALUES(" + productId + ",'" + textNombre3.getText() + "'," + textCantidad3.getText() + "," + textPrecio3.getText() + "," + su + ")");
        }
    }

    private void minimoStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_minimoStockActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_minimoStockActionPerformed

    private void ubicacionStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ubicacionStockActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ubicacionStockActionPerformed

    private void preciocompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_preciocompraActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_preciocompraActionPerformed

    private void salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirActionPerformed
        try {
            /*   model2.removeAllElements();
            model2.clear();*/
            int productId = Integer.parseInt(id_producto.getText());
            ps=cn.prepareStatement("delete from categorias_productos where id_producto = ?");
            ps.setInt(1,productId);
            ps.executeQuery();
            this.dispose();
        } catch (SQLException ex) {
            Almacen.logger.log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_salirActionPerformed

    private void preciocompraKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_preciocompraKeyPressed
// TODO add your handling code here:
    }//GEN-LAST:event_preciocompraKeyPressed

    private void preciocompraKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_preciocompraKeyReleased
        estimarGanancia();
    }//GEN-LAST:event_preciocompraKeyReleased
float porcentajeMayoreos(int num) {
        switch (num) {
            case 1:
                return 10;
            case 2:
                return 15;
            case 3:
                return 20;
            case 4:
                return 25;
            case 5:
                return 30;
            default:
                return 5;
        }
    }
private void estimarGanancia() {
        if (!preciocompra.getText().equals("")) {
            float cantidad, total;
            String porcentaje = (String) comboPorcentaje.getSelectedItem();
            cantidad = Float.parseFloat(preciocompra.getText());
            total = cantidad;
            total *= Integer.valueOf(porcentaje.substring(0, porcentaje.length() - 1));
            total /= 100;
            total += cantidad;
            precio1.setText(formatter.format(total));
        }
    }
    private void comboPorcentajePopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_comboPorcentajePopupMenuWillBecomeInvisible
estimarGanancia();
        
    }//GEN-LAST:event_comboPorcentajePopupMenuWillBecomeInvisible

    private void comboPorcentajeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboPorcentajeActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_comboPorcentajeActionPerformed

    private void activoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_activoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_activoActionPerformed

    private void tipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tipoActionPerformed
        if (!Almacen.celulares) {
            if (tipo.getSelectedIndex() != 2) {
                fecha.setEnabled(false);
            } else {
                fecha.setEnabled(true);
            }
        } else {
            if (tipo.getSelectedIndex() != 0) {
                jPanel1.setVisible(false);
            } else {
                jPanel1.setVisible(true);
            }
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_tipoActionPerformed

    private void categoriasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categoriasActionPerformed
         ArrayList<Integer> ids = new ArrayList(1);
         ids.add(codigo);
        Categorias categoria = new Categorias(this, true, ids);
        categoria.setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_categoriasActionPerformed

    private void imageButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_imageButtonActionPerformed
        FileNameExtensionFilter filtro = new FileNameExtensionFilter(
                "JPG, PNG & GIF", "jpg", "gif", "jpeg", "png");
        fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
        fileChooser.setFileFilter(filtro);
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                Image img = ImageIO.read(fileChooser.getSelectedFile());
                Image resized = img.getScaledInstance(250, 140, 10);
                ImageIcon icon = new ImageIcon(resized);
                hayImagen = true;
                imageProduct.setIcon(icon);
            } catch (IOException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }
        }
    }//GEN-LAST:event_imageButtonActionPerformed

    private void comboSucursalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboSucursalActionPerformed
        if (comboSucursal.getSelectedIndex() != 0) {
            ubicacionStock.setEnabled(true);
            cantidadStock.setEnabled(true);
            minimoStock.setEnabled(true);
        } else {
            ubicacionStock.setEnabled(false);
            cantidadStock.setEnabled(false);
            minimoStock.setEnabled(false);
        }
    }//GEN-LAST:event_comboSucursalActionPerformed

    private void textPrecio1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textPrecio1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textPrecio1ActionPerformed

    private void textNombre1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNombre1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textNombre1ActionPerformed

    private void textNombre2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNombre2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textNombre2ActionPerformed

    private void textCantidad2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textCantidad2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textCantidad2ActionPerformed

    private void textNombre3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textNombre3ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_textNombre3ActionPerformed

    private void fechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fechaActionPerformed
        cambiarFecha fechass = new cambiarFecha(this, true, codigo);
        fechass.setVisible(true);
    }//GEN-LAST:event_fechaActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        (new agregarProvedor(this, true, 0)).setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void descuento2PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_descuento2PopupMenuWillBecomeInvisible
if (!precio1.getText().equals("")) {
    if(textPrecio1.getText().equals(""))textPrecio1.setText("0.00");
    float origen = Float.parseFloat(textPrecio1.getText());
                            precio2.setText(formatter.format(origen - origen * porcentajeMayoreos(descuento2.getSelectedIndex()) / 100));
                        }
        // TODO add your handling code here:
    }//GEN-LAST:event_descuento2PopupMenuWillBecomeInvisible

    private void descuento3PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_descuento3PopupMenuWillBecomeInvisible
if (!precio1.getText().equals("")) {
    if(textPrecio1.getText().equals(""))textPrecio1.setText("0.00");
    float origen = Float.parseFloat(textPrecio1.getText());
                            precio3.setText(formatter.format(origen - origen * porcentajeMayoreos(descuento3.getSelectedIndex()) / 100));
                        }
        // TODO add your handling code here:
    }//GEN-LAST:event_descuento3PopupMenuWillBecomeInvisible

    private void precio1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_precio1PropertyChange

        // TODO add your handling code here:
    }//GEN-LAST:event_precio1PropertyChange

    private void textPrecio1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textPrecio1KeyReleased
if (!textPrecio1.getText().equals("")) {
    float origen = Float.parseFloat(textPrecio1.getText());
                            precio3.setText(formatter.format(origen - origen * porcentajeMayoreos(descuento3.getSelectedIndex()) / 100));
                            precio2.setText(formatter.format(origen - origen * porcentajeMayoreos(descuento2.getSelectedIndex()) / 100));
                        }
        // TODO add your handling code here:
    }//GEN-LAST:event_textPrecio1KeyReleased

    /*
     void sugerenciasMayoreos() {
     if (!precio_unitario.getText().equals("")) {
     jLabel33.setText(String.valueOf(Float.parseFloat(precio_unitario.getText()) - Float.parseFloat(precio_unitario.getText()) * porcentajeMayoreos(jComboBox3.getSelectedIndex()) / 100) + '0');
     jLabel34.setText(String.valueOf(Float.parseFloat(precio_unitario.getText()) - Float.parseFloat(precio_unitario.getText()) * porcentajeMayoreos(jComboBox4.getSelectedIndex()) / 100) + '0');
     jLabel15.setText(String.valueOf(Float.parseFloat(precio_unitario.getText()) - Float.parseFloat(precio_unitario.getText()) * porcentajeMayoreos(jComboBox1.getSelectedIndex()) / 100) + '0');
     } else {
     jLabel33.setText("");
     }
     }*/
    class LimitadorCaracteres extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!(Character.isDigit(arg1.charAt(i)) || arg1.charAt(i) == '.')) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
class LimitadorCaracteresInt extends PlainDocument {

        /**
         * Método al que llama el editor cada vez que se intenta insertar
         * caracteres. Sólo debemos verificar arg1, que es la cadena que se
         * quiere insertar en el JTextField
         */
        public void insertString(int arg0, String arg1, AttributeSet arg2) throws BadLocationException {
            for (int i = 0; i < arg1.length(); i++) // si no es digit, volvemos
            {
                if (!(Character.isDigit(arg1.charAt(i)) )) {
                    return;
                }
            }

            // Si todos son digit, insertamos el texto en el JTextField
            super.insertString(arg0, arg1, arg2);
        }
    }
    public static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }

    public static void cargarProveedores() {
        try {
            comboProveedor.removeAllItems();
            comboProveedor.addItem("Ninguno");
            cn = local_connection.getconnect();
            PreparedStatement psl;
            psl = (PreparedStatement) cn.prepareStatement("SELECT concat(nombre,' ',paterno,' ',materno) FROM personas WHERE tipo ='Proveedor'");
            ResultSet rsl = psl.executeQuery();
            while (rsl.next()) {
                comboProveedor.addItem(rsl.getString("concat(nombre,' ',paterno,' ',materno)"));
            }
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox activo;
    private javax.swing.JTextField cantidadStock;
    private javax.swing.JButton categorias;
    private javax.swing.JComboBox comboPorcentaje;
    private static javax.swing.JComboBox comboProveedor;
    private javax.swing.JComboBox comboSucursal;
    private javax.swing.JComboBox comboTipoProducto;
    private javax.swing.JTextArea descripcion;
    private javax.swing.JComboBox descuento2;
    private javax.swing.JComboBox descuento3;
    private javax.swing.JButton fecha;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JButton guardar;
    private javax.swing.JLabel id_producto;
    private javax.swing.JButton imageButton;
    private javax.swing.JLabel imageProduct;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel labelSugerido;
    private javax.swing.JTextField marca;
    private javax.swing.JTextField minimoStock;
    private javax.swing.JTextField modelo;
    private javax.swing.JTextField nombre;
    private javax.swing.JTextArea notas;
    private javax.swing.JTextField peso;
    private javax.swing.JLabel precio1;
    private javax.swing.JLabel precio2;
    private javax.swing.JLabel precio3;
    private javax.swing.JTextField preciocompra;
    private javax.swing.JButton salir;
    private javax.swing.JTextField textCantidad1;
    private javax.swing.JTextField textCantidad2;
    private javax.swing.JTextField textCantidad3;
    private javax.swing.JTextField textNombre1;
    private javax.swing.JTextField textNombre2;
    private javax.swing.JTextField textNombre3;
    private javax.swing.JTextField textPrecio1;
    private javax.swing.JTextField textPrecio2;
    private javax.swing.JTextField textPrecio3;
    private javax.swing.JComboBox tipo;
    private javax.swing.JTextField ubicacionStock;
    // End of variables declaration//GEN-END:variables
}
